//
//  SheetVC.swift
//  AG
//
//  Created by zhuxuhong on 2020/10/20.
//  Copyright © 2020 3moon. All rights reserved.
//

import BWListKit

class SheetVC: PannelVC {
    override var contentView: UIView {
        return listView
    }
    
    override var contentViewHeight: CGFloat{
        listAdapter.data = _rebuildListData(data)
        let h = listAdapter.data!.totalHeight + Lets.homeIndicatorH
        return h
    }
    
    public lazy var listView: CollectionView = {
        let v = CollectionView()
        v.contentInset = .zero
        v.zCornersEnabled = true
        v.zCornersSets = "1,2"
        v.zCornersRadii = .init(width: 16, height: 16)
        return v
    }()
    
    private lazy var listAdapter: BWListAdapter = {
        return BWListAdapter(collectionView: listView)
    }()
    
    open var data: BWListData {
        return .init(registers: [], sections: [])
    }
    
    open var needsCancelItem: Bool {
        return true
    }
}

extension SheetVC {
    public func defaultItem(withCell reuseId: String, data: Any, height: CGFloat = 50, tapped: Handler.TVoid?) -> BWListItem {
        return .init(reuseId: reuseId, height: height, data: data, action: .init(didSelectItem: { [weak self] _ in
            self?.close{ tapped?() }
        }))
    }
    
    public func defaultTextItem(withData data: SheetTextCell.Data, height: CGFloat = 54, tapped: Handler.TVoid?) -> BWListItem {
        return item(withCell: SheetTextCell.RID, data: data, height: height, tapped: tapped)
    }
    
    public func defaultTitleView(title: String, height: CGFloat = 40) -> BWListHeaderFooter {
        return .init(reuseId: SheetTitleView.RID, height: height, data: title)
    }
    
    public func defaultIconTextItem(withData data: SheetIconTextCell.Data, height: CGFloat = 54, tapped: Handler.TVoid?) -> BWListItem {
        return item(withCell: SheetIconTextCell.RID, data: data, height: height, tapped: tapped)
    }
    
    private func _rebuildListData(_ data: BWListData) -> BWListData {
        let tmpData = BWListData()
        
        var tmpRegisters: [BWListRegister] = []
        var tmpSections: [BWListSection] = data.sections ?? []
        
        if let registers = data.registers {
            tmpRegisters.append(contentsOf: registers)
        }
        
        /// 追加分割线、取消按钮
        tmpRegisters.append(.init(style: .header, class: SheetSeparatorView.self))
        if needsCancelItem {
            tmpRegisters.append(.init(style: .cell, class: SheetCancelCell.self))
            let canelItem = item(withCell: SheetCancelCell.RID, data: SheetCancelCell.Data(title: "取消", style: .cancel)) {[weak self] in
                self?.close()
            }
            tmpSections.append(.init(items: [canelItem]))
        }
        
        tmpData.registers = tmpRegisters
        tmpData.sections = tmpSections
        return tmpData
    }
    
}
